<?php

namespace app\api\logic;

use think\facade\Db;
use app\data\util\HttpUtil;
use think\exception\ValidateException;
use think\facade\Cache;
use app\api\logic\FeiShuTalkLogic;
use app\api\logic\FeiShuMessageLogic;
use think\cache\driver\Redis;

class ApireamazeLogic
{
    public function __construct()
    {

    }

    /**
    * @desc    Apireamaze
    * @date    2024/7/16
    * @author  zhangheng
    */
    public function index($params=[])
    {
        $email        = Config('Logisticskey.apireamaze.email');
        $token        = Config('Logisticskey.apireamaze.token');
        // 消息列表
        // Cache::store('redis')->set('ApireamazePage', 1, 3600 * 24*30);
        $page = Cache::store('redis')->get('ApireamazePage');
        if($page == "-1"){
            return json(DefaultResponse(200, true, '已拉取完成', ''));
        }
        if(empty($page)){
            $page = 1;
        }
        $url = 'https://SheCurve.reamaze.io/api/v1/conversations?page='.$page.'&filter=all&sort=updated_at';
        $return = HttpUtil::getUrlReamaze($url, ['email' => $email, 'token' => $token]);
        // halt($return);
        if(isset($return['conversations']) && !empty($return['conversations'])){
            $conversations = $return['conversations'];
            $count = 0;
            foreach($conversations as $key => $val){
                $count++;
                $insert = [
                    'subject'           => $this->removeNonAscii($val['subject']),
                    'slug'              => $val['slug'],
                    'status'              => $val['status'] ?? "",
                    'author'            => $this->removeNonAscii($val['author']['name']),
                    'message_count'     => $val['message_count'],
                    'created_at'        => $val['created_at'],
                    'updated_at'        => $val['updated_at'],
                    'json'              => $this->removeNonAscii(json_encode($val,true)),
                ];
                $slug = Db::name('conversations')->where(['slug' => $val['slug']])->find();
                if($slug){
                    break;
                }else{
                    Db::name('conversations')->insert($insert);
                }
            }
            // if($count == 30){
                $page = $page + 1;
                Cache::store('redis')->set('ApireamazePage', $page, 3600 * 24*30);
            // }else{
            // if($page >= 30){
                // $page = "-1";
                // Cache::store('redis')->set('ApireamazePage', $page, 3600 * 3);
            // }
        }
        return json(DefaultResponse(200, true, '操作成功', $page));
    }


    public function removeNonAscii($string) {  
        $output = '';  
        for ($i = 0; $i < mb_strlen($string, 'UTF-8'); $i++) {  
            $char = mb_substr($string, $i, 1, 'UTF-8');  
            if (ord($char[0]) < 128) {  
                $output .= $char;  
            }  
        }  
        return $output;  
    } 

    
    /**
    * @desc    info
    * @date    2024/7/16
    * @author  zhangheng
    */
    public function info($params=[])
    {
        //channel分类
        // $url = 'https://SheCurve.reamaze.io/api/v1/reports/channel_summary';

        $email        = Config('Logisticskey.apireamaze.email');
        $token        = Config('Logisticskey.apireamaze.token');
        //邮箱搜索
        $url = 'https://SheCurve.reamaze.io/api/v1/conversations?page=1&filter=open&sort=updated_at&for=msnancybeavers@gmail.com';
        $return = HttpUtil::getUrlReamaze($url, ['email' => $email, 'token' => $token]);
        if(isset($return['conversations']) && !empty($return['conversations'])){
            $conversations = $return['conversations'];
            foreach($conversations as $key => $val){
                if($key == 0){
                    continue;
                }
                $this->conversations_update($val['slug']);
            }
        }
        return json(DefaultResponse(200, true, '操作成功', $return));
    }

    public function conversations_update($slug)
    {
        $email        = Config('Logisticskey.apireamaze.email');
        $token        = Config('Logisticskey.apireamaze.token');
        //邮箱搜索
        $url = 'https://SheCurve.reamaze.io/api/v1/conversations/'.$slug;
        $data['conversation']['status'] = 2;
        $return = HttpUtil::putUrlReamaze($url,$data, ['email' => $email, 'token' => $token]);
        return true;
        // halt($return);
    }


    /**
    * @desc    Apireamaze
    * @date    2024/7/16
    * @author  zhangheng
    */
    public function contacts($params=[])
    {
        $email        = Config('Logisticskey.apireamaze.email');
        $token        = Config('Logisticskey.apireamaze.token');
        // 消息列表
        // Cache::store('redis')->set('ApireamazePage', 1, 3600 * 24*30);
        $page = Cache::store('redis')->get('ApireamazePagecontacts');
        if($page == "-1"){
            return json(DefaultResponse(200, true, '已拉取完成', ''));
        }
        if(empty($page)){
            $page = 1;
        }
        $url = 'https://SheCurve.reamaze.io/api/v1/contacts?page='.$page.'&type=email&sort=date';
        $return = HttpUtil::getUrlReamaze($url, ['email' => $email, 'token' => $token]);
        if(isset($return['contacts']) && !empty($return['contacts'])){
            $contacts = $return['contacts'];
            $count = 0;
            foreach($contacts as $key => $val){
                $count++;
                $insert = [
                    'name'              => $val['name'],
                    'created_at'            => $val['created_at'] ?? "",
                    'email'            => $val['email'] ?? "",
                    'contact_id'            => $val['_id'] ?? "",
                ];
                $slug = Db::name('contacts')->where(['contact_id' => $val['contact_id']])->find();
                if($slug){
                    break;
                }else{
                    Db::name('contacts')->insert($insert);
                }
            }
            $page = $page + 1;
            Cache::store('redis')->set('ApireamazePagecontacts', $page, 3600 * 24*30);
        }
        return json(DefaultResponse(200, true, '操作成功', $page));
    }
    

}
